package com.zhixin.fans.ks.manager;

import android.arch.lifecycle.LiveData;
import android.support.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.tencent.mmkv.MMKV;
import com.zhixin.fans.ks.KeyConstant;
import com.zhixin.fans.ks.api.res.UserInfo;

public class UserInfoManager extends LiveData<UserInfo> {


    @Override
    public void setValue(UserInfo value) {
        super.setValue(value);
    }

    @Override
    protected void postValue(UserInfo value) {
        super.postValue(value);
    }


    public UserInfo load() {
        UserInfo userInfo = JSON.parseObject(MMKV.defaultMMKV().getString(KeyConstant.KEY_USER_INFO, "{}"), UserInfo.class);
        return userInfo;
    }

    public void update() {
        UserInfo userInfo = JSON.parseObject(MMKV.defaultMMKV().getString(KeyConstant.KEY_USER_INFO, "{}"), UserInfo.class);
        setValue(userInfo);
    }


    public boolean save(UserInfo userInfo) {
        setValue(userInfo);
        return MMKV.defaultMMKV().putString(KeyConstant.KEY_USER_INFO, JSON.toJSONString(userInfo)).commit();
    }


    public boolean isLogin() {
        UserInfo userInfo = JSON.parseObject(MMKV.defaultMMKV().getString(KeyConstant.KEY_USER_INFO, "{}"), UserInfo.class);
        return (userInfo != null) && userInfo.getU_id() > 0;
    }

    public boolean logout() {
        return MMKV.defaultMMKV().remove(KeyConstant.KEY_USER_INFO).commit();
    }


    @Nullable
    @Override
    public UserInfo getValue() {
        UserInfo userInfo = super.getValue();
        if (userInfo == null) {
            return load();
        }
        return userInfo;
    }
}
